<script setup lang="ts">
import { reactive, ref } from 'vue';
import FlowCanvas from './components/FlowCanvas.vue';
import Sidebar from './components/Sidebar.vue';
import type { Connection, Node } from './types/index';

// 状态
const nodes = ref<Node[]>([]);

const connections = ref<Connection[]>([]);

const canvasRef = ref<any>(null);
const showNodeDialog = ref(false);
const editingNode = ref<Node | null>(null);
const canUndo = ref(false);
const canRedo = ref(false);

// 表单数据
const nodeForm = reactive({
  title: '',
  icon: '',
  color: '#409EFF',
});

// 方法
const handleNodeDragStart = (nodeType: string) => {
  // 节点拖拽开始逻辑
  console.log('Node drag start:', nodeType);
};

const handleNodeClick = (node: Node, event: MouseEvent) => {
  if (event.ctrlKey || event.metaKey) {
    // 多选逻辑
    console.log('Multi-select node:', node.id);
  } else {
    editingNode.value = node;
    nodeForm.title = node.title;
    nodeForm.icon = node.icon;
    nodeForm.color = node.color;
    showNodeDialog.value = true;
  }
};

const handleNodeUpdate = (node: Node) => {
  console.log('Node update:', node);
  const index = nodes.value.findIndex(n => n.id === node.id);
  if (index !== -1) {
    nodes.value[index] = { ...node };
  } else {
    nodes.value.push(node);
  }
  console.log('Nodes after update:', nodes.value);
};

const handleNodeDelete = (nodeId: string) => {
  nodes.value = nodes.value.filter(node => node.id !== nodeId);
  connections.value = connections.value.filter(
    conn => conn.sourceId !== nodeId && conn.targetId !== nodeId
  );
};

const handleConnectionCreate = (connection: Connection) => {
  connections.value.push(connection);
};

const handleConnectionDelete = (connectionId: string) => {
  connections.value = connections.value.filter(conn => conn.id !== connectionId);
};

const handleConnectionUpdate = (connection: Connection) => {
  const index = connections.value.findIndex(conn => conn.id === connection.id);
  if (index !== -1) {
    connections.value[index] = { ...connection };
  }
};

const handleNodeDialogConfirm = () => {
  if (editingNode.value) {
    handleNodeUpdate({
      ...editingNode.value,
      title: nodeForm.title,
      icon: nodeForm.icon,
      color: nodeForm.color,
    });
  }
  showNodeDialog.value = false;
};

const handleUndo = () => {
  // TODO: 实现撤销功能
  console.log('Undo');
};

const handleRedo = () => {
  // TODO: 实现重做功能
  console.log('Redo');
};

const handleSave = () => {
  const data = {
    nodes: nodes.value,
    connections: connections.value,
  };

  // 节点数据可以发送到服务器端保存
  console.log('节点数据准备发送到服务器:', data);

  // 示例：使用API将数据发送到服务器
  // fetch('/api/workflows', {
  //   method: 'POST',
  //   headers: { 'Content-Type': 'application/json' },
  //   body: JSON.stringify(data)
  // })
  // .then(response => response.json())
  // .then(result => {
  //   console.log('Flow saved to server:', result);
  // })
  // .catch(error => {
  //   console.error('Error saving flow:', error);
  // });
};

const handleLoad = () => {
  // 从服务器加载数据
  console.log('准备从服务器加载节点数据');

  // 示例：从API获取数据
  // fetch('/api/workflows/123')
  //   .then(response => response.json())
  //   .then(data => {
  //     nodes.value = data.nodes;
  //     connections.value = data.connections;
  //     console.log('Flow loaded from server');
  //   })
  //   .catch(error => {
  //     console.error('Error loading flow:', error);
  //   });
};

const handleZoomIn = () => {
  canvasRef.value?.zoomIn();
};

const handleZoomOut = () => {
  canvasRef.value?.zoomOut();
};

const handleZoomFit = () => {
  canvasRef.value?.zoomToFit();
};

const updateNodes = (newNodes: Node[]) => {
  // 只在节点数组实际发生变化时才更新
  if (JSON.stringify(nodes.value) !== JSON.stringify(newNodes)) {
    nodes.value = newNodes.map(node => ({
      ...node,
      position: {
        x: Math.round(node.position.x),
        y: Math.round(node.position.y)
      }
    }));
  }
};

const updateConnections = (newConnections: Connection[]) => {
  // 只在连接数组实际发生变化时才更新
  if (JSON.stringify(connections.value) !== JSON.stringify(newConnections)) {
    connections.value = newConnections;
  }
};

const handleNodeSelect = (nodeId: string | null) => {
  // TODO: 实现节点配置面板
  console.log('Selected node:', nodeId);
};
</script>

<template>
  <div class="app">
    <Sidebar />
    <div class="main-content">
      <FlowCanvas ref="canvasRef" :nodes="nodes" :connections="connections" @update:nodes="updateNodes"
        @update:connections="updateConnections" @node-select="handleNodeSelect" />
    </div>
  </div>
</template>

<style>
html,
body {
  margin: 0;
  padding: 0;
  height: 100%;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial,
    'Noto Sans', sans-serif;
}

.app {
  height: 100vh;
  display: flex;
  background: #f8f9fa;
}

.main-content {
  flex: 1;
  height: 100%;
  overflow: hidden;
  position: relative;
}
</style>